<template>
    <rx-layout>
        <div slot="left" width="210" showButton="true" :headerTitle="i18n('list.processClassify','流程分类')">
            <rx-fit style="padding: 4px;">
                <rx-category-treeeditor
                    cat-key="BPM"
                    :statisticConfig="statisticConfig"
                    read-key="def.read"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :isBpmDefList="true"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center">
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">

                    <div class="table-operator">
                        <a-button type="primary" v-if="findAuthRight('def.add')" icon="plus" @click="handleDesign">
                            {{i18n('list.newProcess','新建流程')}}
                        </a-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('BPM',selectedRows,'pkId','name','appId','treeId',changeAppId)">
                            {{i18n('list.changeApp','变更应用')}}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                        <a-dropdown>
                            <a-button> {{i18n('list.more','更多')}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">

                                <a-menu-item key="1" @click="delByIds(selectedRowKeys)"
                                             v-if="findAuthRight('def.delete') && removeEnable && selectedRowKeys.length > 0">
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                                <a-menu-item key="2" @click="doExport"><i class="iconfont icondaochu icstyl"></i>{{$ti18('rxList.exportBtn','导出')}}
                                </a-menu-item>
                                <a-menu-item key="3" @click="doImport"><i class="iconfont icondaoru icstyl"></i>{{$ti18('rxList.importBtn','导入')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="4"
                                    @click="changeExport(exportConf)"
                                    v-if="selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="switcher"/>
                                    {{$ti18('rxList.changeExport','切换导出')}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>

                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
              </span>
                </div>

                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="$ti18('rxList.title','标题')">
                                    <a-input :placeholder="commonInput('rxList.title','标题','rxDecorator.input')" v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.code','编码')">
                                    <a-input :placeholder="i18n('form.code','编码','input')" v-model="queryParam.Q_KEY__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.status','状态')">
                                    <a-select style="width: 100%" :placeholder="i18n('form.status','状态','select')"
                                              v-model="queryParam.Q_STATUS__S_EQ">
                                        <a-select-option value="">{{i18n('pleaseSelect','请选择')}}</a-select-option>
                                        <a-select-option value="DRAFT">{{i18n('draft','草稿')}}</a-select-option>
                                        <a-select-option value="DEPLOYED">{{i18n('deploy','发布')}}</a-select-option>
                                        <a-select-option value="INVALID">{{i18n('invalid','作废')}}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    bordered
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-bpm/bpm/core/bpmDef/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="defId"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                <span slot="status" slot-scope="{text}">
                  <a-tag
                      :color="text==='DEPLOYED' ? 'green' : 'red'">
                    <span v-if="text==='DEPLOYED'">{{i18n('deploy','发布')}}</span>
                    <span v-else-if="text==='DRAFT'">{{i18n('draft','草稿')}}</span>
                    <span v-else-if="text==='INVALID'">{{i18n('invalid','作废')}}</span>
                  </a-tag>
                </span>
                <span slot="isExport" slot-scope="{ text, record }">
                    <a-tag :color="text == 1 ? 'green' : 'red'">
                        <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                    </a-tag>
                </span>
                <span slot="action" slot-scope="{text, record}" class="actionIcons">
                    <span v-show="findAuthRight('def.design')" @click.stop="handleDesign(record)" :title="i18n('list.design','设计')">{{i18n('list.design','设计')}}</span>
                    <span v-show="(findAuthRight('def.start') || findAuthRight('start.read')) && record.status=='DEPLOYED'" @click.stop="startFlow(record)" :title="i18n('list.start','启动')">{{i18n('list.start','启动')}}</span>
                    <span v-show="record.status==='DEPLOYED'" @click.stop="bpmPreview(record)" :title="i18n('list.processSim','流程仿真')">{{i18n('list.processSim','流程仿真')}}</span>
                    <span @click.stop="copyDef(record)" :title="$ti18('rxForm.copy','复制')">{{$ti18('rxForm.copy','复制')}}</span>
                    <span @click.stop="showImage(record)" :title="i18n('list.tree','流程图')">{{i18n('list.tree','流程图')}}</span>
                    <span @click.stop="clearInst(record.defId)" :title="i18n('list.clearData','清除数据')">{{i18n('list.clearData','清除数据')}}</span>
                    <span v-show="findAuthRight('def.delete') && removeEnable"
                          @click.stop="delByIds([record.defId])" :title="$ti18('rxList.delBtn','清除数据')">{{$ti18('rxList.delBtn','删除')}}</span>
                    <span v-show="record.status!='INVALID'" @click.stop="discardById(record.defId)" :title="i18n('invalid','作废')">{{i18n('invalid','作废')}}</span>
                    <span v-show="record.status=='INVALID'" @click.stop="recoverById(record.defId)" :title="i18n('list.restore','恢复')">{{i18n('list.restore','恢复')}}</span>
                    <span @click.stop="deployMenu(record,false)" :title="i18n('list.deployMenu','发布菜单') + 'KEY'">{{i18n('list.deployMenu','发布菜单')}}KEY</span>
                    <span @click.stop="deployMenu(record,true)" :title="i18n('list.deployMenu','发布菜单') + 'ID'">{{i18n('list.deployMenu','发布菜单')}}ID</span>
                    <span @click.stop="handleAuth(record)" :title="i18n('list.authList','授权列表')">{{i18n('list.authList','授权列表')}}</span>
                    <span @click.stop="deployTaskMenu(record)" :title="i18n('list.deployTaskMenu','发布待办菜单')">{{i18n('list.deployTaskMenu','发布待办菜单')}}</span>
                    <span @click="setExport(record,exportConf)" :title="record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                    <span @click="setIsCount(record)" :title="record.isCount == 0 ? i18n('list.enableSta','开启统计') : i18n('list.closeSta','关闭统计')">{{record.isCount == 0 ? i18n('list.enableSta','开启统计') : i18n('list.closeSta','关闭统计')}}</span>
                </span>
                </rx-grid>
                <a-modal
                    :title="i18n('list.selectInit','选择流程仿真发起人')"
                    style="top: 100px;"
                    :width="400"
                    v-model="visible"
                    :confirmLoading="confirmLoading"
                    @ok="handleOk"
                >
                    <rx-user-component :single="true" v-model="startUser" style="width:100%"></rx-user-component>
                </a-modal>
            </rx-fit>
        </div>
    </rx-layout>

</template>

<script>
import BpmDefApi from '@/api/bpm/core/bpmDef'
import BpmDefNodeApi from '@/api/bpm/core/bpmDefNodeCount'
import BpmImageView from "../comps/BpmImageView";
import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
import {RxLayout, Util, RxFit, RxGrid, BaseList,RxUserComponent} from '@lowcode/jpaas-common-lib'
import BpmDefImport from "./BpmDefImport";
import BpmDefCopy from "./BpmDefCopy";
import BpmInstStart from "./BpmInstStart.vue";
import DialogBox from "../../../../assets/js/DialogBox";
import FlowUtil from "@/views/modules/bpm/js/FlowUtil.js";
import changeAppJs from "@/views/modules/share/changeApp";
import SysTreeApi from "@/api/system/core/sysTree";
import { mapState} from 'vuex';

import exportApp from "@/views/modules/share/exportApp";
import selectNodeDialog from "@/views/modules/bpm/core/SelectNodeDialog.vue";
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import SysAppApi from "@/api/system/core/sysApp";
import {openUrl} from "@/utils/util";
import switchExport from "@/utils/switchExport";
import ChangeCategory from "@/views/modules/share/ChangeCategory.js"


export default {
    name: 'BpmDefList',
    mixins: [BaseList, FlowUtil,changeAppJs,AppSearch,switchExport,ChangeCategory],
    components: {
        RxLayout,
        RxFit,
        RxGrid,
        RxCategoryTreeeditor,
        RxUserComponent,
        exportApp,
        RxSearchApp
    },
    data() {
        return {
            // 查询参数
            queryParam: {},
            // 表头
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'},
                    width: 60
                },
                {
                    title: this.$ti18('rxList.title','标题'),
                    dataIndex: 'name',
                    width: 200
                },
                {
                    title: this.i18n('form.code','编码'),
                    dataIndex: 'key',
                    width: 120
                },
                {
                    title: this.i18n('form.status','状态'),
                    dataIndex: 'status',
                    width: 70,
                    scopedSlots: {customRender: 'status'}
                },
                {
                    title: this.i18n('form.version','版本号'),
                    dataIndex: 'version',
                    width: 70
                },
                {
                    dataIndex: 'isExport',
                    slots: { title: 'exportApp' },
                    width: 100,
                    scopedSlots: {customRender: 'isExport'}
                },
                {
                    title: this.$ti18('rxForm.createTime','创建时间'),
                    dataIndex: 'createTime',
                    width: 120
                },
                {
                    title: this.$ti18('rxList.action','操作'),
                    dataIndex: 'action',
                    fixed: 'right',
                    scopedSlots: {customRender: 'action'},
                    width: 120
                }
            ],
            curTree: {},
            visible: false,
            confirmLoading: false,
            startUser:[],
            selectBpmDef:"",
            statisticConfig: {
                type:"static_bpm",
                table:"BPM_DEF t",
                field:"TREE_ID_",
                whereConf:[{name:"IS_MAIN_",type:"string",dateFormat:"",op:"=",value:"YES"}]
            },
            exportApp:true,
            /**
             * 导出配置
             */
            exportConf:{
                Api:BpmDefApi,
                id:"defId"
            },
            //变更分类配置
            categoryConfig:{
                Api:BpmDefApi,
                catKey:"BPM",
                gridRef:"table"
            },
            //选中左边树分类的id
            selectedTreeId:'',
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.needFilterAppId("isAppMenu");
    },
    methods: {
        // 设置是否开启流程统计
        setIsCount(record) {
            var self_ = this;
            if (record.isCount!=1){
                BpmDefApi.getNodesByActDefId(record.actDefId).then(res => {
                    console.log(res);
                    var nodes = res.data;
                    var conf = {
                        component: selectNodeDialog,
                        title: this.i18n("defNodeMsg.selectNode","请选择要统计的流程节点"),
                        curVm: this,
                        data: {nodes: nodes},
                        widthHeight: ['800px', '600px']
                    };
                    Util.open(conf, function (action,data) {
                        if (action != 'ok') {
                            return;
                        }
                        //点击确定，启动流程统计
                        let param = {
                            defId: record.defId,
                            isCount: record.isCount == 1 ? 0 : 1
                        };
                        BpmDefApi.update(param).then(res => {
                            if (res.success) {
                                self_.$message.success(res.message);
                                self_.loadData();
                            } else {
                                self_.$message.error(self_.exportI18n('export.settingFail','设置失败！'));
                            }
                        });
                        //记录那些开启统计的节点
                        BpmDefNodeApi.saveNodesCount(record.defId,record.actDefId,data)

                    });
                });
            }else {
                //点击确定，关闭流程统计
                let param = {
                    defId: record.defId,
                    isCount: record.isCount == 1 ? 0 : 1
                };
                BpmDefApi.update(param).then(res => {
                    if (res.success) {
                        self_.$message.success(res.message);
                        //关闭统计时删除流程节点统计表里的数据
                        BpmDefNodeApi.deleByDefId(record.defId)
                        self_.loadData();
                    } else {
                        self_.$message.error(self_.exportI18n('export.settingFail','设置失败！'));
                    }

                });
            }




        },
        exportI18n(name,text,key){
            return this.$ti18(name,text,"appExport",key);
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmDef",key);
        },
        commonInput(name,text,key){
            let value = this.$ti18(name,text);

            let input = this.$ti18(key,text);
            return input + ' ' + value;
        },
        doExport() {
            let exportList = this.$refs.table.getSelectedRows();
            if (!exportList || exportList.length == 0) {
                this.$confirm({
                    title: this.i18n('warning','警告'),
                    content: this.i18n('selectRecord','请选择需要导出的记录！'),
                    cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                    okText: this.$ti18('rxForm.okBtn','确定')
                });
                return;
            }
            let defIds = [];
            exportList.forEach(item => {
                defIds.push(item.defId);
            });
            BpmDefApi.doExport(defIds);
        },
        doImport() {
            // if(!this.curTree || !this.curTree.treeId || this.curTree.treeId=='0'){
            //   this.$confirm({
            //     title: '警告',
            //     content: '请选择流程方案的分类!！',
            //     cancelText: '取消',
            //     okText:'确定'
            //   });
            //   return;
            // }
            //var treeId = this.curTree.treeId;
            Util.open({
                component: BpmDefImport,
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: this.i18n('list.processImport','流程导入'),
                data: {
                    //treeId:treeId
                }
            }, function (action) {
            });
        },
        handSelect(curRow) {
            this.curTree = curRow;
            let treeId = curRow.treeId;
            this.selectedTreeId = treeId;
            if (treeId != "0") {
                this.queryParam.Q_TREE_ID__S_EQ = treeId;
            } else {
                delete this.queryParam.Q_TREE_ID__S_EQ;
            }
            this.loadData(this.queryParam);
        },
        showImage(record) {
            Util.open({
                component: BpmImageView,
                curVm: this,
                widthHeight: ['1024px', '600px'],
                title: record.name + this.i18n('list.tree','流程图'),
                data: {
                    defId: record.defId
                }
            }, function (action) {
            });
        },
        //启动流程
        startFlow(record) {
            this.startProcess(record.key,record.appId);
        },
        clearInst(defId) {
            this.$confirm({
                title: this.i18n('warning','警告'),
                content: this.i18n('sureToClear','确认清除流程相关实例数据吗？'),
                okText: this.$ti18('rxForm.okBtn','确定'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmDefApi.clearInstByDefId(defId);
                },
                onCancel() {
                },
            });

        },
        handleDesign(record) {
            let self_=this;
            //新建流程之前判断是否有分类
            SysTreeApi.getByCatKey('BPM', self_.curApp.appId).then((res) => {
                if (res.length>0){
                    //存在分类节点，允许新建流程
                    let url = BpmDefApi.designBaseUrl;
                    let json={};
                    if (record && record.defId) {
                        json.defId= record.defId;
                    }
                    if(self_.curApp.appId){
                        json.appId=self_.curApp.appId;
                    }
                    if(self_.selectedTreeId && self_.selectedTreeId!=0){
                        json.treeId = self_.selectedTreeId
                    }
                    let params=Util.jsonToUrl(json);
                    if(params){
                        url+="?" + params;
                    }
                    window.open(url);
                }else {
                    //没有分类节点，报错
                    this.$message.error(this.i18n('newCategory','请先新建分类'));
                }
            })

        },
        //流程作废
        discardById(defId) {
            let self_=this;

            this.$confirm({
                title: this.i18n('sureToVoid','确认要作废？'),
                content: h => this.i18n('sureInvalid','确定要作废该流程定义？'),
                onOk() {
                    BpmDefApi.discard(defId).then((res)=>{
                        self_.$refs.table.onRefresh();
                    });
                }
            });
        },
        recoverById(defId) {
            let self_=this
            this.$confirm({
                title: this.i18n('sureRestore','确认要恢复？'),
                content: h => this.i18n('sureResBpm','确定要恢复该流程定义？'),
                onOk() {
                    BpmDefApi.recover(defId).then(res=>{
                        self_.$refs.table.onRefresh();
                    });
                }
            });
        },
        delById(ids) {
            return BpmDefApi.del(ids.join(','));
        },
        copyAddDef() {
            let row = this.$refs.table.getSelectedRow();
            if (!row) {
                alert(this.i18n('selectRec','请选择一条记录'));
            } else {
                this.copyDef(row);
            }
        },
        copyDef(row) {
            let self = this;
            Util.open({
                component: BpmDefCopy,
                curVm: this,
                widthHeight: ['700px', '400px'],
                title: this.i18n('list.processCopy','流程定义拷贝') + '--' + row.name,
                data: {
                    pkId: row.defId
                }
            }, function (action) {
                self.refreshGrid();
            });
        },
        search() {
            this.$refs.table.loadData();
        },
        cancel() {
            this.resetSearch();
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        deployMenu(record, deployId) {
            var component = 'modules/bpm/OpenDoc/BpmInstStart';
            var params = deployId ? {defId: record.defId} : {defKey: record.key};
            DialogBox.openDeploymenuDialog({
                    curAppObj:this.curApp,
                    releaseId: record.defId,
                    name: record.name,
                    key: record.key + "Flow",
                    settingType: "custom",
                    component: component,
                    params: JSON.stringify(params),
                },
                {
                    curVm: this,
                    widthHeight: ['600px', '600px'],
                });
        },
        handleAuth(record){
            this.$router.push({
                name:"bpmAuthByProcess",
                params:{defKey:record.key},
                query:{appId:record.appId}
            });
        },
        deployTaskMenu(record) {
            var component = 'modules/bpm/ws/MyTaskByDefKey';
            var params = {"defKey": record.key, "defColumn": true};
            DialogBox.openDeploymenuDialog({
                    curAppObj:this.curApp,
                    releaseId: record.defId,
                    name: record.name,
                    key: record.key + "_Task",
                    component: component,
                    params: JSON.stringify(params),
                },
                {
                    curVm: this,
                    widthHeight: ['600px', '600px'],
                });
        },
        bpmPreview(record) {
            this.selectBpmDef=record;
            this.startUser=[];
            this.visible=true;
        },
        handleOk() {
            if (this.startUser.length==0 || !this.startUser[0].id) {
                this.$message.error(this.i18n('selectInitor','请选择发起人！'))
                return;
            }
            this.visible=false;
            let record=this.selectBpmDef;
            let appId=record.appId;
            SysAppApi.get(appId).then(res=>{
              let app=res.data;
              let path=app.path;
              let url=`${path}/${app.clientCode}/new/${record.key}?appId=${appId}&preview=true&startUserId=${this.startUser[0].id}`;
              let title=record.name;
              openUrl({url:url,title:title,curVm:this,max:true});
            })
        },
        changeAppId(selectedRows){
            BpmDefApi.saveList(selectedRows);
        }
    }
}
</script>
<style scoped>

</style>